# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 学员视图

学员管理相关的路由处理
包括学员CRUD操作、档案管理等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.forms.student_forms import (
    StudentSearchForm, StudentEditForm, StudentProfileForm,
    StudentBatchForm, StudentDeleteForm, StudentCoachApplicationForm
)
from app.controllers.student_controller import StudentController
from app.utils.decorators import admin_required, super_admin_required

# 创建学员蓝图
students_bp = Blueprint('students', __name__)


@students_bp.route('/')
@students_bp.route('/list')
@admin_required
def list():
    """
    学员列表页

    支持搜索、筛选、分页功能
    """
    form = StudentSearchForm()

    # 获取搜索参数
    page = request.args.get('page', 1, type=int)
    keyword = request.args.get('keyword', '')
    campus_id = request.args.get('campus_id', '', type=str)
    status = request.args.get('status', '')
    has_coach = request.args.get('has_coach', '')
    sort_by = request.args.get('sort_by', 'created_at_desc')

    # 转换campus_id
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None

    # 设置表单默认值
    if request.method == 'GET':
        form.keyword.data = keyword
        form.campus_id.data = campus_id
        form.status.data = status
        form.has_coach.data = has_coach
        form.sort_by.data = sort_by

    # 获取学员列表
    pagination, total = StudentController.get_student_list(
        page=page,
        per_page=12,
        keyword=keyword,
        campus_id=campus_id,
        status=status,
        has_coach=has_coach,
        sort_by=sort_by
    )

    # 获取汇总统计
    summary = StudentController.get_campus_student_summary(campus_id)

    return render_template(
        'students/list.html',
        form=form,
        pagination=pagination,
        students=pagination.items,
        total=total,
        summary=summary
    )


@students_bp.route('/<int:id>')
@admin_required
def detail(id):
    """
    学员详情页

    显示学员完整信息和统计数据
    """
    student = StudentController.get_student_by_id(id)
    if not student:
        flash('学员不存在或无权限访问', 'error')
        return redirect(url_for('students.list'))

    # 获取学员统计信息
    statistics = StudentController.get_student_statistics(id)

    # 获取教练列表
    coaches = StudentController.get_student_coaches(id)

    # 获取最近的预约记录
    recent_reservations = StudentController.get_student_recent_reservations(id)

    return render_template(
        'students/detail.html',
        student=student,
        statistics=statistics,
        coaches=coaches,
        recent_reservations=recent_reservations
    )


@students_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@admin_required
def edit(id):
    """
    编辑学员页

    校区管理员可以编辑自己校区的学员
    超级管理员可以编辑任意学员
    """
    student = StudentController.get_student_by_id(id)
    if not student:
        flash('学员不存在或无权限访问', 'error')
        return redirect(url_for('students.list'))

    form = StudentEditForm(student=student)

    if request.method == 'GET':
        # 填充表单数据
        form.real_name.data = student.real_name
        form.phone.data = student.phone
        form.email.data = student.email
        form.gender.data = student.gender
        form.age.data = student.age
        form.campus_id.data = student.campus_id
        form.status.data = student.status
        # 如果有notes字段
        if hasattr(student, 'notes'):
            form.notes.data = student.notes

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'real_name': form.real_name.data,
                'phone': form.phone.data,
                'email': form.email.data,
                'gender': form.gender.data,
                'age': form.age.data,
                'campus_id': form.campus_id.data,
                'status': form.status.data,
                'notes': form.notes.data,
                'photo': form.photo.data
            }

            # 更新学员
            success, error_msg = StudentController.update_student(student, form_data)

            if success:
                flash(f'学员"{student.real_name}"信息更新成功！', 'success')
                return redirect(url_for('students.detail', id=student.id))
            else:
                flash(f'更新失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('students/edit.html', form=form, student=student)


@students_bp.route('/<int:id>/profile', methods=['GET', 'POST'])
@login_required
def profile(id):
    """
    学员档案页

    学员可以编辑自己的档案信息
    管理员可以查看学员档案
    """
    student = StudentController.get_student_by_id(id)
    if not student:
        flash('学员不存在或无权限访问', 'error')
        return redirect(url_for('students.list'))

    # 权限检查：只有学员本人或管理员可以访问
    if not (current_user.id == id or current_user.is_super_admin() or current_user.is_campus_admin()):
        flash('无权限访问此页面', 'error')
        return redirect(url_for('dashboard.index'))

    # 学员本人可以编辑，管理员只能查看
    can_edit = (current_user.id == id)

    if can_edit:
        form = StudentProfileForm()

        if request.method == 'GET':
            form.real_name.data = student.real_name
            form.email.data = student.email
            form.gender.data = student.gender
            form.age.data = student.age

        if request.method == 'POST':
            if form.validate_on_submit():
                # 获取表单数据
                form_data = {
                    'real_name': form.real_name.data,
                    'email': form.email.data,
                    'gender': form.gender.data,
                    'age': form.age.data,
                    'photo': form.photo.data
                }

                # 更新档案
                success, error_msg = StudentController.update_student(student, form_data)

                if success:
                    flash('档案更新成功！', 'success')
                    return redirect(url_for('students.profile', id=id))
                else:
                    flash(f'更新失败：{error_msg}', 'error')
            else:
                for field, errors in form.errors.items():
                    for error in errors:
                        flash(f'{form[field].label.text}: {error}', 'error')
    else:
        form = None

    # 获取统计信息
    statistics = StudentController.get_student_statistics(id)

    # 获取教练和预约信息
    coaches = StudentController.get_student_coaches(id)
    recent_reservations = StudentController.get_student_recent_reservations(id, limit=5)

    return render_template(
        'students/profile.html',
        student=student,
        form=form,
        can_edit=can_edit,
        statistics=statistics,
        coaches=coaches,
        recent_reservations=recent_reservations
    )


@students_bp.route('/<int:id>/delete', methods=['GET', 'POST'])
@admin_required
def delete(id):
    """
    删除学员页

    需要确认删除操作
    """
    student = StudentController.get_student_by_id(id)
    if not student:
        flash('学员不存在或无权限访问', 'error')
        return redirect(url_for('students.list'))

    form = StudentDeleteForm()
    form.student_id.data = id

    if request.method == 'POST':
        if form.validate_on_submit():
            success, error_msg = StudentController.delete_student(id)

            if success:
                flash(f'学员"{student.real_name}"已删除', 'success')
                return redirect(url_for('students.list'))
            else:
                flash(f'删除失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    # 获取关联数据信息
    associations = StudentController.check_student_associations(id)

    return render_template(
        'students/delete_confirm.html',
        form=form,
        student=student,
        associations=associations
    )


@students_bp.route('/batch', methods=['POST'])
@admin_required
def batch_operation():
    """
    批量操作学员

    支持批量状态更新、校区转移等
    """
    form = StudentBatchForm()

    if form.validate_on_submit():
        try:
            student_ids = [int(id.strip()) for id in form.student_ids.data.split(',') if id.strip()]
            action = form.action.data

            kwargs = {}
            if action == 'transfer_campus':
                kwargs['target_campus_id'] = form.target_campus_id.data

            success_count, fail_count, errors = StudentController.batch_operation(
                student_ids, action, **kwargs
            )

            # 构建结果消息
            if success_count > 0:
                action_text = {
                    'activate': '激活',
                    'deactivate': '停用',
                    'delete': '删除',
                    'transfer_campus': '转移校区'
                }.get(action, '操作')
                flash(f'成功{action_text}{success_count}个学员', 'success')

            if fail_count > 0:
                flash(f'{fail_count}个学员操作失败', 'warning')
                for error in errors[:5]:  # 只显示前5个错误
                    flash(error, 'error')

        except Exception as e:
            flash(f'批量操作失败：{str(e)}', 'error')
    else:
        # 显示表单验证错误
        for field, errors in form.errors.items():
            for error in errors:
                flash(error, 'error')

    return redirect(url_for('students.list'))


@students_bp.route('/api/search')
@admin_required
def api_search():
    """
    学员搜索API

    用于AJAX请求获取学员列表
    """
    keyword = request.args.get('keyword', '')
    campus_id = request.args.get('campus_id', '', type=str)
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 12, type=int)

    try:
        pagination, total = StudentController.get_student_list(
            page=page,
            per_page=per_page,
            keyword=keyword,
            campus_id=campus_id
        )

        students_data = []
        for student in pagination.items:
            students_data.append({
                'id': student.id,
                'real_name': student.real_name,
                'phone': student.phone,
                'campus_name': student.campus.name if student.campus else '',
                'status': student.status,
                'status_display': {
                    'active': '活跃',
                    'inactive': '不活跃'
                }.get(student.status, ''),
                'created_at': student.created_at.strftime('%Y-%m-%d') if student.created_at else '',
                'last_login_at': student.created_at.strftime('%Y-%m-%d') if student.created_at else '从未登录'
            })

        return jsonify({
            'success': True,
            'data': students_data,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_prev': pagination.has_prev,
                'has_next': pagination.has_next
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@students_bp.route('/api/<int:id>/statistics')
@admin_required
def api_statistics(id):
    """
    学员统计API

    获取学员的统计信息
    """
    student = StudentController.get_student_by_id(id)
    if not student:
        return jsonify({'success': False, 'error': '学员不存在或无权限访问'}), 404

    try:
        statistics = StudentController.get_student_statistics(id)
        return jsonify({
            'success': True,
            'data': statistics
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@students_bp.route('/api/summary')
@admin_required
def api_summary():
    """
    学员汇总统计API

    获取校区的学员汇总信息
    """
    campus_id = request.args.get('campus_id', '', type=str)
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None

    try:
        summary = StudentController.get_campus_student_summary(campus_id)
        return jsonify({
            'success': True,
            'data': summary
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@students_bp.route('/<int:id>/apply-coach', methods=['GET', 'POST'])
@login_required
def apply_coach(id):
    """
    学员申请教练

    学员可以申请选择教练
    """
    # 权限检查：只有学员本人可以申请
    if current_user.id != id or not current_user.is_student():
        flash('无权限执行此操作', 'error')
        return redirect(url_for('dashboard.index'))

    student = StudentController.get_student_by_id(id)
    if not student:
        flash('学员不存在', 'error')
        return redirect(url_for('dashboard.index'))

    form = StudentCoachApplicationForm(student=student)

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                from app.models.relation import StudentCoachRelation

                # 创建师生关系申请
                relation = StudentCoachRelation(
                    student_id=id,
                    coach_id=form.coach_id.data,
                    apply_note=form.apply_note.data,
                    status='pending'
                )

                db.session.add(relation)
                db.session.commit()

                flash('申请已提交，请等待教练审核', 'success')
                return redirect(url_for('students.profile', id=id))

            except Exception as e:
                db.session.rollback()
                flash(f'申请失败：{str(e)}', 'error')
        else:
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template(
        'students/apply_coach.html',
        form=form,
        student=student
    )